package com.openatc.agent.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author ：panleilei
 * @description
 * @modified By：
 * @version:
 * @date ：Created in 2023/6/5 10:35
 */
@Configuration
public class CustomizeSchemaInitializer implements BeanPostProcessor {
    @Value("${schema:public}")
    private String schemaName;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 项目启动后，jpa数据库表创建前，创建schema
        if (bean instanceof JpaBaseConfiguration) {
            String auth2Sql = String.format("CREATE SCHEMA IF NOT EXISTS auth2 ");
//            String specialSchemaSql = String.format("CREATE SCHEMA IF NOT EXISTS %s ",schemaName);
            if ("public".equals(schemaName)) {
                jdbcTemplate.batchUpdate(auth2Sql);
            } else {
                String[] schemas = schemaName.split(",");
                String[] sqls = new String[schemas.length + 1];
                for (int i = 0; i < schemas.length; i++) {
                    sqls[i] = String.format("CREATE SCHEMA IF NOT EXISTS %s ",schemas[i]);
                }
                sqls[schemas.length] = auth2Sql;
                jdbcTemplate.batchUpdate(sqls);
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
